<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/lonie233/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/lonie233/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/lonie233/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/lonie233/images/logo.svg" color="#222">

<link rel="stylesheet" href="/lonie233/css/main.css">


<link rel="stylesheet" href="/lonie233/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lonie233.gitee.io","root":"/lonie233/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="摘要其实消息交付语义 并不是kafka独有的，而是每一个“消息系统”都会面临的问题，业界抽象出三种语义  最多一次（at most once）：某个消息最多被消费一次 最少一次（at least once）：某个消息最少被消费一次 精准一次（exactly once）：某个消息被消费且仅被消费一次  其实很容易做出取舍，最好的肯定是精准一次，其次是最少一次，因为收到多次肯定比一次都收不到强，因为收">
<meta property="og:type" content="article">
<meta property="og:title" content="Kafka消息交付语义">
<meta property="og:url" content="https://lonie233.gitee.io/2021/03/31/kafka-msg-delivery/index.html">
<meta property="og:site_name" content="Welcome">
<meta property="og:description" content="摘要其实消息交付语义 并不是kafka独有的，而是每一个“消息系统”都会面临的问题，业界抽象出三种语义  最多一次（at most once）：某个消息最多被消费一次 最少一次（at least once）：某个消息最少被消费一次 精准一次（exactly once）：某个消息被消费且仅被消费一次  其实很容易做出取舍，最好的肯定是精准一次，其次是最少一次，因为收到多次肯定比一次都收不到强，因为收">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-03-31T03:05:37.000Z">
<meta property="article:modified_time" content="2021-12-16T06:31:33.598Z">
<meta property="article:author" content="lonie">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://lonie233.gitee.io/2021/03/31/kafka-msg-delivery/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Kafka消息交付语义 | Welcome</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-193107295-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-193107295-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/lonie233/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Welcome</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/lonie233/" rel="section"><i class="home  //首页 fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/lonie233/about/" rel="section"><i class="user  //关于 fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/lonie233/tags/" rel="section"><i class="tags  //标签 fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/lonie233/categories/" rel="section"><i class="th   //分类 fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/lonie233/archives/" rel="section"><i class="archive //归档 fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/lonie233/schedule/" rel="section"><i class="calendar   //日程表 fa-fw"></i>日程表</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/lonie233/sitemap.xml" rel="section"><i class="sitemap   //站点地图 fa-fw"></i>站点地图</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    

  <a href="https://gitee.com/lonie233/lonie233" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lonie233.gitee.io/2021/03/31/kafka-msg-delivery/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/lonie233/images/avatar.jpg">
      <meta itemprop="name" content="lonie">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Welcome">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Kafka消息交付语义
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-31 11:05:37" itemprop="dateCreated datePublished" datetime="2021-03-31T11:05:37+08:00">2021-03-31</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-12-16 14:31:33" itemprop="dateModified" datetime="2021-12-16T14:31:33+08:00">2021-12-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/lonie233/categories/Kafka/" itemprop="url" rel="index"><span itemprop="name">Kafka</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>1.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>1 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="摘要"><a href="#摘要" class="headerlink" title="摘要"></a>摘要</h3><p>其实<strong>消息交付语义</strong> 并不是kafka独有的，而是每一个“消息系统”都会面临的问题，业界抽象出三种语义</p>
<ul>
<li>最多一次（at most once）：某个消息最多被消费一次</li>
<li>最少一次（at least once）：某个消息最少被消费一次</li>
<li>精准一次（exactly once）：某个消息被消费且仅被消费一次</li>
</ul>
<p>其实很容易做出取舍，最好的肯定是精准一次，其次是最少一次，因为收到多次肯定比一次都收不到强，因为收到多次，消费端还可以可以根据消息内容进行幂等处理进行兼容。而最多一次，基本不会采用，因为会丢消息</p>
<p>Kafka 目前有很多版本，默认的消息交付语义是最少一次，而在0.11.0.0 版本之后支持了精准一次，本文主要介绍了Kafka精准一次的实现思路</p>
<p>如有问题，欢迎gitee 提 issue，共同进步</p>
<a id="more"></a>

<h3 id="精准一次"><a href="#精准一次" class="headerlink" title="精准一次"></a>精准一次</h3><p>其实摘要里的精准一次的定义是狭义的，并不完全。因为只从Consumer定义了精准消费一次，Producer同样面临精准一次的问题。</p>
<h4 id="Producer-侧"><a href="#Producer-侧" class="headerlink" title="Producer 侧"></a>Producer 侧</h4><p>在Kafka默认策略里，为了保证消息不丢失，Producer 没有收到Broker返回的消息接收成功通知时，会重新发送消息，这对Producer和Broker来说，意味着此时的交付语义是至少一次，无法满足精准一次的定义，即消息投递且仅被投递一次，针对这个问题，kafka从0.11.0.0 开始，每个Producer 都被分配一个，同时每个producer 生产的每条消息都会有一个序列号，在Kafka 内部会根据这个对消息进行去重，这样每个消息即使被投递多次，也只会被存储一次</p>
<p>这样的话，你也许会问，那Producer 并不是发送一次啊，还是可能发送多次。是的，遇到网络抖动导致无法收到Broker返回时，确实是会重复发送，但是重点是不会重复存储，也就不会出现重复的消息，间接的实现了精准一次。</p>
<p>另外Kafka额外有事务型的操作，假设同时发个多个Topic的消息，可以做到要么都发送成功，要么都发送不成功。但是需要注意的事，这类操作会更加的耗时，如果需要及时响应的服务，不建议这么使用</p>
<h4 id="Consumer侧"><a href="#Consumer侧" class="headerlink" title="Consumer侧"></a>Consumer侧</h4><p>消费侧有两种策略</p>
<ol>
<li>先记录消费进度，再执行真正的消费逻辑。这样的风险在于，消费进度记录了，但是执行消费逻辑之前挂了，服务重启之后，根据消费进度，会跳过处理之前消费失败的消息，也就会导致消息丢失，属于至多消费一次</li>
<li>先消费，再记录进度。风险在于消费完了，没来的及记录进度。服务重启之后，查询进度，会重新再消费一次，属于至少消费一次</li>
</ol>
<p>kafka 是怎么实现精准消费一次的呢？</p>
<p>分成两种情况</p>
<ol>
<li>消费的逻辑是把TopicA的消息a转换成TopicB的消息b重新发给Kafka，这种情况下，TopicA的消费进度会附在TopicB的消息内，利用Producer 的事务发送机制，一旦发送异常，则不更新或者回滚TopicA 的消费进度，这样的话，消息a下次还会被消费。同时消息b也不一定会被消费（需要设置“隔离级别”）。消费者默认的隔离级别是读未提交，只要有消息就可以被看到，需要调整成读已提交，这样就只能看到事务提交之后的消息了</li>
<li>消费的逻辑依赖外部系统。这种情况下需要实现两个逻辑来保证业务的正确性<ol>
<li>保证消息消费的幂等性</li>
<li>把消费进度的提交和业务处理在业务系统内捆绑成一个事务，保证消费进度提交失败时回滚事务</li>
</ol>
</li>
</ol>
<p>其实本质上来说，都是选择了先消费，再记录。只是增加了记录失败时回滚消费逻辑的能力。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>这里贴一段对kafka官方的翻译吧</p>
<p>kafka 自身在Kafka-Stream 支持精准一次的消费，同时事务性的Producer 和 Consumer 时可用的当处理Kafka内部流转消息在不同Topic。精准一次对于其他系统来说往往需要进行协同开发，但是Kafka提供了offset机制使得这些开发更加容易（参考Kafka-Stream）。其他情况下，Kafka默认提供的是至少消费一次的语义，当然，也支持使用者禁止Producer重试 和调整提交消费进度的逻辑来实现至多消费一次的语义</p>
<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><p><a target="_blank" rel="noopener" href="https://kafka.apache.org/documentation/#semantics">Kafka-消息交付语义</a></p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/lonie233/2021/03/30/kafka-high-reliability/" rel="prev" title="kafka-高可靠性">
      <i class="fa fa-chevron-left"></i> kafka-高可靠性
    </a></div>
      <div class="post-nav-item">
    <a href="/lonie233/2021/04/01/kafka-classic-question/" rel="next" title="kafka经典问题">
      kafka经典问题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%91%98%E8%A6%81"><span class="nav-number">1.</span> <span class="nav-text">摘要</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B2%BE%E5%87%86%E4%B8%80%E6%AC%A1"><span class="nav-number">2.</span> <span class="nav-text">精准一次</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Producer-%E4%BE%A7"><span class="nav-number">2.1.</span> <span class="nav-text">Producer 侧</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Consumer%E4%BE%A7"><span class="nav-number">2.2.</span> <span class="nav-text">Consumer侧</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">4.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="lonie"
      src="/lonie233/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">lonie</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/lonie233/archives/">
        
          <span class="site-state-item-count">14</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/lonie233/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/loniecc" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;loniecc" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huzeming2019@outlook.com" title="E-Mail → mailto:huzeming2019@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lonie</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">12k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11 分钟</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lonie233/lib/anime.min.js"></script>
  <script src="/lonie233/lib/velocity/velocity.min.js"></script>
  <script src="/lonie233/lib/velocity/velocity.ui.min.js"></script>

<script src="/lonie233/js/utils.js"></script>

<script src="/lonie233/js/motion.js"></script>


<script src="/lonie233/js/schemes/pisces.js"></script>


<script src="/lonie233/js/next-boot.js"></script>




  















  

  

</body>
</html>
